//
//  QGHelpSendViewController.m
//  QuanGou
//
//  Created by qqqq on 15/11/19.
//  Copyright © 2015年 DongYongFei. All rights reserved.
//

#import "QGHelpSendViewController.h"
#import <PhotoTweaksViewController.h>

#import <CoreLocation/CoreLocation.h>

@interface QGHelpSendViewController ()<UIImagePickerControllerDelegate,UINavigationControllerDelegate,PhotoTweaksViewControllerDelegate,CLLocationManagerDelegate,UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UITextField *titleTextField;

@property (weak, nonatomic) IBOutlet UITextField *phoneNumberTextField;
@property (weak, nonatomic) IBOutlet UITextField *addressTextField;
@property (weak, nonatomic) IBOutlet UITextView *detailTextView;
@property (weak, nonatomic) IBOutlet UIImageView *picture;
@property (nonatomic, strong) UIButton *button;
/**
 *  获取地理位置
 */
//@property (copy, nonatomic) NSString *localtion;
//@property (nonatomic ,strong) CLLocationManager *locationManager;
/**
 *  经纬度
 */
@property (copy, nonatomic) NSString *latitude;
@property (copy, nonatomic) NSString *longitude;
@end

@implementation QGHelpSendViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.detailTextView.layer.backgroundColor = [[UIColor clearColor] CGColor];
    self.detailTextView.layer.borderColor = [[UIColor colorWithRed:230.0/255.0 green:250.0/255.0 blue:250.0/255.0 alpha:1.0]CGColor];
    self.detailTextView.layer.borderWidth = 3.0;
    self.detailTextView.layer.cornerRadius = 8.0f;
    [self.detailTextView.layer setMasksToBounds:YES];
    
    self.titleTextField.delegate = self;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapClick:)];
    [self.view addGestureRecognizer:tap];
    
    self.picture.userInteractionEnabled = YES;
    UILongPressGestureRecognizer *longPress = [[UILongPressGestureRecognizer alloc] initWithTarget:self action:@selector(prepareDeletePicture:)];
    [self.picture addGestureRecognizer:longPress];

    
}
#pragma mark - 点击手势关闭键盘
- (void)tapClick:(UITapGestureRecognizer *)tap {
    [self.view endEditing:YES];
}
- (void)prepareDeletePicture:(UILongPressGestureRecognizer *)longPress {
    if (longPress.state == UIGestureRecognizerStateBegan) {
        self.button = [UIButton buttonWithType:(UIButtonTypeSystem)];
        self.button.frame = CGRectMake(CGRectGetWidth(self.picture.frame) - 30, 5, 30, 30);
        [self.button setImage:[UIImage imageNamed:@"delete"] forState:(UIControlStateNormal)];

        [self.picture addSubview:self.button];
        [self.button addTarget:self action:@selector(deletePicture) forControlEvents:(UIControlEventTouchUpInside)];
    }
}
- (void)deletePicture {
    [self.button removeFromSuperview];
    self.button = nil;
    self.picture.image = nil;
}

#pragma mark - 添加图片 从相册 相机 并修饰
- (IBAction)pushPictureButton:(UIButton *)sender {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:(UIAlertControllerStyleActionSheet)];
    UIAlertAction *phontoListAction = [UIAlertAction actionWithTitle:@"从相册选取" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = NO;
        
        [self showDetailViewController:imagePicker sender:nil];
        
    }];
    UIAlertAction *camereAction = [UIAlertAction actionWithTitle:@"从相机拍照选择" style:(UIAlertActionStyleDefault) handler:^(UIAlertAction * _Nonnull action) {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType = UIImagePickerControllerSourceTypeCamera;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = NO;
        
        [self showDetailViewController:imagePicker sender:nil];
    }];
    UIAlertAction *cancleAction = [UIAlertAction actionWithTitle:@"取消" style:(UIAlertActionStyleCancel) handler:nil];
    
    [alertController addAction:phontoListAction];
    [alertController addAction:camereAction];
    [alertController addAction:cancleAction];
    [self presentViewController:alertController animated:YES completion:nil];
}
#pragma mark - 相册的delegate
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *)info {
    
    UIImage *image = [info objectForKey:UIImagePickerControllerOriginalImage];
    PhotoTweaksViewController *photoTweaksViewController = [[PhotoTweaksViewController alloc] initWithImage:image];
    photoTweaksViewController.delegate = self;
    [picker presentViewController:photoTweaksViewController animated:YES completion:nil];
    
}
#pragma mark - 修饰照片的delegate
- (void)photoTweaksController:(PhotoTweaksViewController *)controller didFinishWithCroppedImage:(UIImage *)croppedImage{
    
    self.picture.image = croppedImage;
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)photoTweaksControllerDidCancel:(PhotoTweaksViewController *)controller {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    if(range.location >= 25)
    {
        return NO;
    }else return YES;
}

#pragma mark - 提交并加到数据库
- (IBAction)sendHelpButton:(UIButton *)sender {
//    if (self.phoneNumberTextField.text == nil || [self.phoneNumberTextField.text isEqualToString:@""]) {
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"警告" message:@"为了让别人能够更好的帮助你，请填写全面的信息" preferredStyle:(UIAlertControllerStyleAlert)];
//        UIAlertAction *alertAction = [UIAlertAction actionWithTitle:@"确定" style:(UIAlertActionStyleDefault) handler:nil];
//        [alertController addAction:alertAction];
//        [self presentViewController:alertController animated:YES completion:nil];
//        return;
//    }
    
    
    
    AVObject *sendHelp = [AVObject objectWithClassName:@"HelpSendModel"];
    [sendHelp setObject:[AVUser currentUser].objectId forKey:@"userId"];
    [sendHelp setObject:self.phoneNumberTextField.text forKey:@"phoneNumber"];
    [sendHelp setObject:self.titleTextField.text forKey:@"title"];
    [sendHelp setObject:self.addressTextField.text forKey:@"address"];
    [sendHelp setObject:self.detailTextView.text forKey:@"detailInfo"];
    [sendHelp setObject:@"未接收" forKey:@"state"];
    [sendHelp setObject:[NSString stringWithFormat:@"中国%@",self.addressTextField.text] forKey:@"locationCity"];


    [sendHelp saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        
        CLGeocoder *geocoder = [[CLGeocoder alloc] init];
        //正向地理编码
        [geocoder geocodeAddressString:[NSString stringWithFormat:@"中国%@",self.addressTextField.text] completionHandler:^(NSArray<CLPlacemark *> * _Nullable placemarks, NSError * _Nullable error) {
            CLLocation *location = [[placemarks lastObject] location];

            AVGeoPoint *point = [AVGeoPoint geoPointWithLatitude:location.coordinate.latitude longitude:location.coordinate.longitude];
            [sendHelp setObject:point forKey:@"location"];
            [sendHelp save];
        }];
        
        if (self.picture != nil) {
            NSData *imageData = UIImagePNGRepresentation(self.picture.image);
            AVFile *imageFile = [AVFile fileWithName:[NSString stringWithFormat:@"%@.png", [AVUser currentUser].objectId] data:imageData];
            [imageFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (!error) {
                    [sendHelp setObject:imageFile forKey:@"picture"];
                    [sendHelp save];
                }
            }];
        }
    }];
    

    

#warning 发表成功需要做的操作
}
- (IBAction)backButton:(id)sender {
    [self dismissViewControllerAnimated:YES completion:nil];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
